package com.oneguy.control.message;

import com.oneguy.Cache;
import com.oneguy.Constants;
import com.oneguy.Log;
import com.oneguy.control.timer.TaskManager;
import com.oneguy.control.timer.TimerTask;
import com.oneguy.control.util.JaxbUtil;
import com.oneguy.control.util.TextUtils;
import com.oneguy.control.util.TimeUtil;
import com.oneguy.model.QueryUtil;
import com.oneguy.model.WeixinMessage;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.core.env.Environment;

import java.io.*;
import java.util.*;

/**
 * Created by ZuoShu on 16/12/6.
 */
public class TextHandler {
    private static final String TAG = "TextHandler";

    Environment ev;

    // user name, authority set
    Map<String, Set<String>> authorityMap;

    TaskManager taskManager;

    public TextHandler(Environment ev) {
        this.ev = ev;
        initAuthMap();
    }

    public void setTaskManager(TaskManager taskManager) {
        this.taskManager = taskManager;
    }

    private void initAuthMap() {
        authorityMap = new HashMap<String, Set<String>>();

        String authFilePath = ev.getProperty("authFile");
        File authFile = new File(authFilePath);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(authFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                initAuth(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Log.i(TAG, "auth map:" + authorityMap.toString());
    }

    public Map<String, Set<String>> getAuthorityMap() {
        return authorityMap;
    }

    private void initAuth(String authLine) {
        if (TextUtils.isEmpty(authLine)
                || authLine.startsWith(Constants.COMMENT)) {
            return;
        }

        String[] parts = authLine.split(Constants.EQUAL);
        if (parts == null || parts.length < 2) {
            return;
        }

        String username = parts[0];
        String[] auths = parts[1].split(Constants.COMMA);
        if (auths == null || auths.length == 0) {
            return;
        }

        Set<String> authSet = null;
        if (authorityMap.containsKey(username)) {
            authSet = authorityMap.get(username);
        } else {
            authSet = new HashSet<String>();
        }
        for (String auth : auths) {
            authSet.add(auth);
        }
        authorityMap.put(username, authSet);
    }

    public String handleMessage(WeixinMessage message) {
        if (Constants.C.QUERY_TIME.equals(message.getContent())) {
            return handleQueryTime(message);
        } else if (Constants.C.SZ_QUERY_FISH.equals(message.getContent())) {
            return handleQuerySzFish(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_SET_FISH)) {
            return handleSetSzFish(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_TIMER_SET_FISH)) {
            return handleSetTimerSzFish(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_QUERY_TIMER_SET_FISH)) {
            return handleQueryTimerSzFish(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_CLEAR_QUERY_TIMER)) {
            return handleClearTimerSzFish(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_QUERY_FISH_SCORE)) {
            return handleQuerySzFishScore(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_SET_FISH_SIMPLE)) {
            return handleSetSzFishSimple(message);
        } else if (Constants.C.SZ_QUERY_DATA.equals(message.getContent())) {
            return handleQueryData(message);
        } else if (Constants.C.SZ_FISH_MONITOR.equals(message.getContent())) {
            return handleFishMonitor(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_QUERY_USER_DETAIL)) {
            return handleQueryUserDetail(message);
        } else if (!TextUtils.isEmpty(message.getContent())
                && message.getContent().startsWith(Constants.C.SZ_QUERY_USER_TRANSFER_DETAIL)) {
            return handleQueryUserTransferDetail(message);
        }


        return "";
//        return MessageUtil.getDefaultTip(message);
    }

    // 1000 获取服务器时间
    private String handleQueryTime(WeixinMessage message) {
        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.getServerTimeString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    private String handleQuerySzFish(WeixinMessage message) {
        Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_FISH);
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_FISH)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_FISH + " not Authorized");
            return "";
        }
        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.getSzFishFactorString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    private String handleSetSzFish(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_SET_FISH)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_SET_FISH + " not Authorized");
            return "";
        }

        String[] args = message.getContent().split(Constants.ARG_SPLIT);
        if (args == null || args.length < 4) {
            return MessageUtil.getTipSzSetFishMessage(message);
        }

        String roomId = args[1];
        String firstTableId = args[2];
        String factor = args[3];
        Cache.getInstance().setRoom(roomId, firstTableId, factor);

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent("设置成功 " + roomId + " " + firstTableId + " " + factor);
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 设置松滋捕鱼定时参数
    private String handleSetTimerSzFish(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_TIMER_SET_FISH)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_TIMER_SET_FISH + " not Authorized");
            return "";
        }

        if (taskManager == null || taskManager.isStop()) {
            Log.i(TAG, "timer task stop!can not run task");
            return "";
        }

        String[] args = message.getContent().split(Constants.ARG_SPLIT);
        if (args == null || args.length < 5) {
            return MessageUtil.getTipSzSetFishTimerMessage(message);
        }

        String roomId = args[1];
        String firstTableId = args[2];
        String factor = args[3];
        String time = args[4];
        long timeInLong = TimeUtil.toLongTime(time);
        TimerTask task = new TimerTask(roomId, firstTableId, factor, timeInLong);
        taskManager.addTask(task);

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent("设置成功\n"
                + "房间:" + roomId + "\n"
                + "桌子:" + firstTableId + "\n"
                + "设置:" + factor + "\n"
                + "时间:" + TextUtils.simpleFormatTime(timeInLong));
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1004 查询松滋捕鱼定时参数
    private String handleQueryTimerSzFish(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_TIMER_SET_FISH)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_TIMER_SET_FISH + " not Authorized");
            return "";
        }

        if (taskManager == null || taskManager.isStop()) {
            Log.i(TAG, "timer task stop!can not query task");
            return "";
        }

        List<TimerTask> taskList = taskManager.getTaskList();
        StringBuilder sb = new StringBuilder();
        sb.append("=====捕鱼定时任务:" + (taskList == null ? 0 : taskList.size()) + "\n");
        if (taskList != null && taskList.size() > 0) {
            Collections.sort(taskList);
            int i = 1;
            for (TimerTask task : taskList) {
                sb.append("NO." + i++ + "\n");
                sb.append("房间:" + task.getRoomId() + "\n"
                        + "桌子:" + task.getTableId() + "\n"
                        + "设置:" + task.getFactor() + "\n"
                        + "时间:" + TextUtils.simpleFormatTime(task.getTime()) + "\n");
            }
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(sb.toString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1005 清除松滋捕鱼定时任务
    private String handleClearTimerSzFish(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_CLEAR_QUERY_TIMER)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_CLEAR_QUERY_TIMER + " not Authorized");
            return "";
        }

        if (taskManager == null || taskManager.isStop()) {
            Log.i(TAG, "timer task stop!can not query task");
            return "";
        }
        taskManager.clearTask();

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent("清除成功！");
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1006 松滋 查询捕鱼数据
    private String handleQuerySzFishScore(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_FISH_SCORE)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_FISH_SCORE + " not Authorized");
            return "";
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.getFishDataString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1007 松滋 设置捕鱼参数 简单模式
    private String handleSetSzFishSimple(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_SET_FISH_SIMPLE)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_SET_FISH_SIMPLE + " not Authorized");
            return "";
        }

        String[] args = message.getContent().split(Constants.ARG_SPLIT);
        if (args == null || args.length < 2) {
            return MessageUtil.getTipSzSetFishSimpleMessage(message);
        }

        StringBuilder sb = new StringBuilder();

        String factor1 = args[1];
        String roomId = ev.getProperty("fish.simple.roomid");
        String tableid1 = ev.getProperty("fish.simple.tableid1");
        Cache.getInstance().setRoom(roomId, tableid1, factor1);
        sb.append("设置成功 房间:" + roomId + "\n");
        sb.append("桌子:" + tableid1 + " 参数:" + factor1 + "\n");

        if (args.length >= 3) {
            String factor2 = args[2];
            String tableid2 = ev.getProperty("fish.simple.tableid2");
            Cache.getInstance().setRoom(roomId, tableid2, factor2);
            sb.append("桌子:" + tableid2 + " 参数:" + factor2);
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(sb.toString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1008 查询运营数据
    private String handleQueryData(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_DATA)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_DATA + " not Authorized");
            return "";
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.getSzDataString());
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1009 捕鱼监测
    private String handleFishMonitor(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_FISH_MONITOR)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_FISH_MONITOR + " not Authorized");
            return "";
        }

        String content = "";
        if (Cache.getInstance().hasMonitor(
                Constants.C.SZ_FISH_MONITOR, message.getFromUserName())) {
            Cache.getInstance().removeMonitor(
                    Constants.C.SZ_FISH_MONITOR, message.getFromUserName());
            content = "捕鱼监测关闭";
        } else {
            Cache.getInstance().addMonitor(
                    Constants.C.SZ_FISH_MONITOR, message.getFromUserName());
            content = "捕鱼监测打开";
        }
        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(content);
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1011 查询玩家信息
    private String handleQueryUserDetail(WeixinMessage message) {
        Log.i(TAG, "handleQueryUserDetail:" + message.getContent());
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_USER_DETAIL)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_USER_DETAIL + " not Authorized");
            return "";
        }

        String replyContent = "";
        String[] args = message.getContent().split(Constants.ARG_SPLIT);
        if (args == null || args.length < 2) {
            return buildTip(message, Constants.Tip.TIP_SZ_QUERY_USER_DETAIL);
        }

        String id = args[1];
        int intId = 0;
        try {
            intId = Integer.parseInt(id);
        } catch (Exception e) {
        }
        if (intId == 0) {
            return buildTip(message, Constants.Tip.TIP_SZ_QUERY_USER_DETAIL);
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.queryUserDetail(intId));
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

    // 1012 查询玩家转账详情
    private String handleQueryUserTransferDetail(WeixinMessage message) {
        if (!isAuthorized(message.getFromUserName(), Constants.C.SZ_QUERY_USER_TRANSFER_DETAIL)) {
            Log.i(TAG, "user:" + message.getFromUserName() + " action:" + Constants.C.SZ_QUERY_USER_TRANSFER_DETAIL + " not Authorized");
            return "";
        }
        String[] args = message.getContent().split(Constants.ARG_SPLIT);
        if (args == null || args.length < 2) {
            return buildTip(message, Constants.Tip.TIP_SZ_QUERY_USER_TRANSFER_DETAIL);
        }

        String id = args[1];
        int intId = 0;
        try {
            intId = Integer.parseInt(id);
        } catch (Exception e) {
        }
        if (intId == 0) {
            return buildTip(message, Constants.Tip.TIP_SZ_QUERY_USER_TRANSFER_DETAIL);
        }

        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(QueryUtil.queryUserTransferDetail(intId));
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }


    private boolean isAuthorized(String fromUserName, String szQueryFish) {
        Set<String> authString = authorityMap.get(fromUserName);
        return authString != null && authString.contains(szQueryFish);
    }

    private String buildTip(WeixinMessage message, String tip) {
        WeixinMessage reply = new WeixinMessage();
        reply.setToUserName(message.getFromUserName());
        reply.setFromUserName(message.getToUserName());
        reply.setContent(tip);
        reply.setCreateTime(String.valueOf(System.currentTimeMillis()));
        reply.setMsgType(Constants.T.TEXT);
        Log.i(TAG, "reply message:" + reply);
        return StringEscapeUtils.unescapeXml(JaxbUtil.toXml(reply));
    }

}
